package com.pureut.storage.service.impl;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.storage.domain.*;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.PickingSaleExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.PickingSaleRelationVo;
import com.pureut.storage.vo.PickingSaleVo;
import com.pureut.storage.vo.UpdateDocVo;
import com.pureut.storage.vo.*;
import com.pureut.system.api.*;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysUser;
import com.pureut.system.api.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2022/12/27  14:45
 */
@Service
public class PickingSaleServiceImpl extends ServiceImpl<PickingSaleMapper, PickingSale> implements PickingSaleService {

    /**
     * 销售发货Mapper
     */
    @Resource
    PickingSaleMapper pickingSaleMapper;


    @Resource
    FeignService feignService;

    @Resource
    WarehouseMapper warehouseMapper;

    @Resource
    OrderFeignService orderFeignService;

    @Resource
    ProductionPickingService productionPickingService;


    //单据配置
    @Resource
    private SystemDocumentFeignService systemDocumentFeignService;

    //库存
    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;

    //库存
    @Resource
    WmsStockInfoService wmsStockInfoService;

    //销售发货明细
    @Resource
    PickingSaleDetailMapper pickingSaleDetailMapper;

    @Resource
    PickingSaleDetailService pickingSaleDetailService;

    //公共物料
    @Resource
    PublicGoodsMapper publicGoodsMapper;

    //用户信息
    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private QualityFeginService qualityFeginService;

    @Resource
    private PickingSchemeService pickingSchemeService;

    @Resource
    private OutboundLogService outboundLogService;

    @Resource
    private OutboundLogMapper outboundLogMapper;


    /**
     * 新增销售发货单
     *
     * @param pickingSaleVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addSale(PickingSaleVo pickingSaleVo) throws Exception {
        List<PickingSaleRelationVo> list = pickingSaleVo.getList();


        List<PickingSale> pickingSalelist = new ArrayList<>();
        if (list.size() > 0) {

            for (PickingSaleRelationVo pickingSaleRelationVo : list) {

                String sn = feignService.getAuthorityCoding("warehouse:outbound:shipsale:list");
                if (sn == null) {
                    throw new GlobalException("该单据未进行配置,无法生成单据编码");
                }


                PickingSale pickingSale = new PickingSale();
                BeanUtils.copyProperties(pickingSaleVo, pickingSale);
                BeanUtils.copyProperties(pickingSaleRelationVo, pickingSale);
                pickingSale.setCreateUser(SecurityUtils.getUsername())
                        .setCreateTime(new Date())
                        .setDocumentType(DocumentTypeEnum.PICKING_SALE.getCode())
                        .setWodDocNum(sn)
                        .setDeptId(SecurityUtils.getDeptId())
                        .setWodStatus(1)
                        .setConnectionId(pickingSaleRelationVo.getConnectionId())
                        .setGenerationMode(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                pickingSalelist.add(pickingSale);
            }
            return saveBatch(pickingSalelist);
        } else {
            throw new GlobalException("请至少添加一条物料明细");
        }
    }

    /**
     * 修改销售发货单
     *
     * @param pickingSaleVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSale(PickingSaleVo pickingSaleVo) {

        //查询当前id对应的单据
        PickingSale pickingSale = pickingSaleMapper.selectById(pickingSaleVo.getId());
        int wodStatus = pickingSale.getWodStatus();
        if (wodStatus != 1 && wodStatus != 4) {
            throw new GlobalException("只能对“待提交”,“未通过”状态的单据进行修改");
        }

        if (wodStatus == 4) {

            //调用审核
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            String perms = "warehouse:outbound:shipsale:examine";
            String auditDoc = pickingSale.getWodDocNum();
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setPerms(perms);
            AjaxResult history = feignService.editHistory(sysAuditHistoryVo);
            String data = JSON.parseObject(JSON.toJSONString(history.get("msg")), String.class);
            if ("操作成功".equals(data)) {
                pickingSale.setWodStatus(1);

                //修改审核代办状态为已处理
                feignService.updateStatus(3, pickingSale.getWodDocNum(), "销售发货");//
            }


        }

        List<PickingSaleRelationVo> list = pickingSaleVo.getList();
        PickingSaleRelationVo pickingSaleRelationVo = list.get(0);

        pickingSale.setTransceiverType(pickingSaleVo.getTransceiverType());
        pickingSale.setCustomId(pickingSaleVo.getCustomId());
        pickingSale.setDateDelivery(pickingSaleVo.getDateDelivery());
        pickingSale.setRemark(pickingSaleVo.getRemark());

        pickingSale.setPlannedWeight(pickingSaleRelationVo.getPlannedWeight());
        pickingSale.setOutOfStock(pickingSaleRelationVo.getOutOfStock());
        return updateById(pickingSale);

    }

    /**
     * 关结销售发货单
     *
     * @param pickingSaleVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeSale(PickingSaleVo pickingSaleVo) {
        //查询当前单据的状态，只能对待提交，未通过，待审核，审核中，待出库，待交接，状态的单据进行关结
        PickingSale pickingSale = pickingSaleMapper.selectById(pickingSaleVo.getId());
        //取出当前的单据状态
        int wodStatus = pickingSale.getWodStatus();

        if (wodStatus == 8 || wodStatus == 7) {
            throw new GlobalException("不可对已关结和已完成状态的单据进行重复关结");
        }


        try {
            //如果单据状态是待检验，入库的物料显示在库，关联品质检验单状态更新为撤销
            if (wodStatus == 9 || wodStatus == 10 || wodStatus == 6) {
                //根据单号获取生产领料单明细
                List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                ArrayList<WmsStockInfo> wmsStockInfos = new ArrayList<>();

                for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList) {
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingSaleDetail.getPdoductNumber()));
                    wmsStockInfos.add(wmsStockInfo);
                }

                if (wmsStockInfos.size() != 0) {
                    boolean b = wmsStockInfoService.removeBatchByIds(wmsStockInfos);
                    if (!b) {
                        throw new GlobalException("关结失败");
                    }
                }


                if (wodStatus == 9) {
                    //如果是待检验删除品质检验单
                    UpdateQualityStatusVo updateQualityStatusVo = new UpdateQualityStatusVo();
                    updateQualityStatusVo.setStatus(8);
                    updateQualityStatusVo.setAssociatedNo(pickingSale.getWodDocNum());
                    AjaxResult ajaxResult = qualityFeginService.updateQualityInspectionDocument(updateQualityStatusVo);


                    if (!"200".equals(ajaxResult.get("code").toString())) {
                        throw new GlobalException("服务调用失败");
                    }

                }
            }
        } catch (Exception e) {
            throw new GlobalException("关结失败");
        }


        //取出关结人
        String closeMan = pickingSale.getCloseMan();
        if (closeMan != null) {
            closeMan = closeMan + "," + SecurityUtils.getUsername();
        } else {
            closeMan = SecurityUtils.getUsername();
        }
        //修改单据状态未关结，修改关结原因，修改关结人，修改关结时间
        PickingSale pickingSale1 = new PickingSale();
        pickingSale1.setId(pickingSaleVo.getId())
                .setWodStatus(8).setCloseTime(new Date())
                .setCloseMan(closeMan)
                .setCloseCause(pickingSaleVo.getCloseCause())
                .setCloseTime(new Date());
        return updateById(pickingSale1);

    }

    /**
     * 销售发货删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSale(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        //根据ids批量查询出list列表
        List<PickingSale> pickingSales = pickingSaleMapper.selectBatchIds(idStr);

        //遍历
        for (PickingSale pickingSale : pickingSales) {
            if (pickingSale.getWodStatus() != 1 && pickingSale.getWodStatus() != 4) {
                throw new GlobalException("只能删除“待提交”或“未通过”状态的单据");
            } else if (pickingSale.getGenerationMode() != 2) {
                throw new GlobalException("系统自动生成的单据不可删除");
            }
        }

        for (PickingSale pickingSale : pickingSales) {
            feignService.deleteDoc(pickingSale.getWodDocNum(), "销售发货");
        }
        return removeBatchByIds(idStr);

    }

    /**
     * 提交审核
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitSale(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        //根据ids批量查询出list列表
        List<PickingSale> pickingSales = pickingSaleMapper.selectBatchIds(idStr);

        //遍历
        for (PickingSale pickingSale : pickingSales) {
            if (pickingSale.getWodStatus() != 1) {
                throw new GlobalException("只能对状态为“待提交”的单据进行提交操作");
            }
            pickingSale.setWodStatus(2);

            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
            sysWorkbenchAuditAgentVo.setDocConfig("warehouse:outbound:shipsale:examine");
            sysWorkbenchAuditAgentVo.setReceiptName("销售发货");
            sysWorkbenchAuditAgentVo.setReceiptNumber(pickingSale.getWodDocNum());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);
        }
        return updateBatchById(pickingSales);
    }

    /**
     * 查看单据
     *
     * @param id
     * @return
     */
    @Override
    public PickingSaleDto view(Long id) {
        //查询单条对象
        PickingSaleDto pickingSaleDto = pickingSaleMapper.getPickingSaleById(id);
        //根据字典查询收发类型(成品/半成品)
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_sale_type");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        //添加单据类型
        pickingSaleDto.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(pickingSaleDto.getDocumentType())));
        pickingSaleDto.setDocumentType(pickingSaleDto.getDocumentType());

        //添加收发类型
        pickingSaleDto.setTransceiverType(pickingSaleDto.getTransceiverType() + "");
        pickingSaleDto.setTransceiverTypeDict(statusMap.get(pickingSaleDto.getTransceiverType() + ""));

        List<PickingSaleViewDto> list = new ArrayList<>();

        PickingSaleViewDto pickingSaleViewDto = new PickingSaleViewDto();

        //查看仓库名称
        Warehouse warehouse = warehouseMapper.selectById(pickingSaleDto.getOutOfStock());
        if (warehouse != null) {
            //添加仓库名称
            pickingSaleViewDto.setOutOfStockDict(warehouse.getWarehouseName());
            pickingSaleViewDto.setOutOfStock(pickingSaleDto.getOutOfStock());
        }
        //添加单位key
        pickingSaleViewDto.setMaterialUnitDict(pickingSaleDto.getMaterialUnit() + "");

        //添加单位值
        pickingSaleViewDto.setMaterialUnit(unitMap.get(pickingSaleDto.getMaterialUnit() + ""));

        //添加物料名称，物料规格，物料料号
        pickingSaleViewDto.setMaterialCode(pickingSaleDto.getMaterialCode());
        pickingSaleViewDto.setMaterialName(pickingSaleDto.getItemName());
        pickingSaleViewDto.setMaterialSpec(pickingSaleDto.getItemSpec());

        //添加销售订单号
        pickingSaleViewDto.setConnectionId(pickingSaleDto.getConnectionId());
        //添加计划量
        pickingSaleViewDto.setPlannedWeight(pickingSaleDto.getPlannedWeight());


        list.add(pickingSaleViewDto);
        pickingSaleDto.setList(list);

        return pickingSaleDto;
    }

    /**
     * 销售发货列表查询
     *
     * @param pickingSaleVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<PickingSaleDto> getList(PickingSaleVo pickingSaleVo) {
        //查询销售发货列表
        List<PickingSaleDto> pickingSaleList = pickingSaleMapper.getPickingSaleList(pickingSaleVo);

        //获取单据状态字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_sale_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出收发类型
        List<SysDictData> receivType = DictUtils.getDictCache("picking_sale_type");
        Map<String, String> typeMap = receivType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (PickingSaleDto pickingSaleDto : pickingSaleList) {

            //查看仓库名称
            Warehouse warehouse = warehouseMapper.selectById(pickingSaleDto.getOutOfStock());
            if (warehouse != null) {
                //添加仓库名称
                pickingSaleDto.setOutOfStockDict(warehouse.getWarehouseName());
                pickingSaleDto.setOutOfStock(pickingSaleDto.getOutOfStock());
            }


            //添加单据类型
            pickingSaleDto.setDocumentType(DocumentTypeEnum.getValue(Integer.parseInt(pickingSaleDto.getDocumentType())));

            //添加收发类型
            pickingSaleDto.setTransceiverTypeDict(pickingSaleDto.getTransceiverType() + "");
            pickingSaleDto.setTransceiverType(typeMap.get(pickingSaleDto.getTransceiverType() + ""));


            //添加单据状态
            pickingSaleDto.setWodStatusDict(pickingSaleDto.getWodStatus() + "");
            pickingSaleDto.setWodStatus(statusMap.get(pickingSaleDto.getWodStatus() + ""));

            //添加生产方式
            pickingSaleDto.setGenerationMode(GenerationMethodEnum.getValue(Integer.parseInt(pickingSaleDto.getGenerationMode())));

            //添加单位key
            pickingSaleDto.setMaterialUnitDict(pickingSaleDto.getMaterialUnit() + "");

            //添加单位值
            pickingSaleDto.setMaterialUnit(unitMap.get(pickingSaleDto.getMaterialUnit() + ""));

        }
        return pickingSaleList;
    }


    public List<GetPdaDto> getListPda(PickingSaleVo pickingSaleVo) {
        //查询销售发货列表
        List<GetPdaDto> list = pickingSaleMapper.getPickingSaleListPda(pickingSaleVo);

        //获取单据状态字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_sale_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (GetPdaDto getPdaDto : list) {
            getPdaDto.setWodStatusDict(statusMap.get(getPdaDto.getWodStatus()));
        }

        return list;
    }

    /**
     * @param pickingSaleVo
     * @return
     */
    @Override
    public List<PickingSaleExport> getInfoExport(PickingSaleVo pickingSaleVo) {

        if (pickingSaleVo.getIdStr() != null) {
            List<String> idList = Arrays.asList(pickingSaleVo.getIdStr().split(","));

            pickingSaleVo.setIds(idList);
        }

        List<PickingSaleExport> list = pickingSaleMapper.getInfoExport(pickingSaleVo);

        //根据字典查出收发类型
        List<SysDictData> receivType = DictUtils.getDictCache("picking_sale_type");
        Map<String, String> typeMap = receivType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 网型
        List<SysDictData> meshTypeArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> meshTypeMap = meshTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 铺网类型
        List<SysDictData> layingTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> layingTypeMap = layingTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (PickingSaleExport pickingSaleExport : list) {
            pickingSaleExport.setTransceiverTypeDict(typeMap.get(pickingSaleExport.getTransceiverTypeDict()));
            pickingSaleExport.setMaterialNetDict(meshTypeMap.get(pickingSaleExport.getMaterialNetDict()));
            pickingSaleExport.setMaterialNetDict(layingTypeMap.get(pickingSaleExport.getMaterialNetTypeDict()));
        }

        return list;
    }

    /**
     * 销售发货出库
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto out(PickingRestDbVo pickingRestDbVo) throws Exception {
        //出库类型
        String type = pickingRestDbVo.getType();
        //输入值
        String inputValue = pickingRestDbVo.getInputValue();

        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();

        //判断是否超收或者超发
        //获取菜单id
        Long menuId = feignService.getIdByMenuName("销售发货");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //如果配置了送检,则校验是否配了检验方案
        if (sysDocument.getDocInspectionMark() == 1) {

            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
            if (documentCheckDtoList == null) {
                throw new GlobalException("请先在单据配置中配置送检方案");
            }


            PickingSale byId = getById(pickingRestDbVo.getId());

            //查询单位
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, byId.getMaterialCode()));


            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
            qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
            qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
            qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
            qualitySchemeConfigurationVo.setMaterialCode(byId.getMaterialCode());
            boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

            if (!check) {
                throw new GlobalException("该物料不存在对应的检验方案");

            }
        }

        //如果是扫码出库
        if ("1".equals(type)) {
            //判断扫描的物料条码是否一致
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2));

            if (wmsStockInfo == null) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                return pickingRestDbDto;
            }

            if ("1".equals(wmsStockInfo.getWsiFreezeInfo())) {
                throw new GlobalException("此物料已冻结请重新输入");
            }

            //扫描的物料编码
            String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();
            //查询委外发货单中的物料编码、
            PickingSale pickingSale = pickingSaleMapper.selectById(pickingRestDbVo.getId());

            //查询单位
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));

            if (!pickingSale.getMaterialCode().equals(wsiMaterialCode)) {
                pickingRestDbDto.setMessage("500");
                pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                return pickingRestDbDto;
            }

            //判断是否重复扫描(在明细表中查询是否有该条码)
            PickingSaleDetail pickingSaleDetail1 = pickingSaleDetailMapper.selectOne(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getPdoductNumber, inputValue).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));
            if (pickingSaleDetail1 != null) {
                pickingRestDbDto.setMessage("500");
                pickingRestDbDto.setMessage("请勿重复扫描");
                return pickingRestDbDto;
            }

            PickingSaleDetail pickingSaleDetail = new PickingSaleDetail();
            //物料号码
            pickingSaleDetail.setPdoductNumber(inputValue);

            //物料编码
            pickingSaleDetail.setItemCode(wmsStockInfo.getWsiMaterialCode());

            //物料状态
            pickingSaleDetail.setWodStatus(3);

            //关联单号
            pickingSaleDetail.setWodDocNum(pickingSale.getWodDocNum());

            //毛重
            pickingSaleDetail.setGrossWeight(wmsStockInfo.getWsiGorssWeight());

            //净重
            pickingSaleDetail.setNetWeight(wmsStockInfo.getWsiNetWeight());

            //出库数量
            pickingSaleDetail.setOutgoingNumber(1L);

            //批次号
            pickingSaleDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());


            //厚度
            pickingSaleDetail.setThick(wmsStockInfo.getWsiThick());

            //幅宽
            pickingSaleDetail.setBreadth(wmsStockInfo.getWsiWidth());
            //卷长
            pickingSaleDetail.setRollLength(wmsStockInfo.getWsiLength());


            //仓储信息
            pickingSaleDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());

            //出库人
            pickingSaleDetail.setDepositor(SecurityUtils.getUsername());

            //出库时间
            pickingSaleDetail.setDeliveryTime(new Date());

            //判断是否有检验
            int docInspectionMark = sysDocument.getDocInspectionMark();
            //如果有检验
            if (docInspectionMark == 1) {
                //修改单据明细为待检验
                pickingSaleDetail.setWodStatus(1);
            } else {
                //判断是否有交接
                int docHandoverMark = sysDocument.getDocHandoverMark();
                //有交接
                if (docHandoverMark == 1) {
                    //修改单据明细为待交接
                    pickingSaleDetail.setWodStatus(2);

                }
            }
            //添加明细
            pickingSaleDetailMapper.insert(pickingSaleDetail);

            //修改委外发货单的单据状态为出库中
            pickingSale.setWodStatus(6);
            //修改出库重量和出库数量
            Double outgoingWeight = pickingSale.getOutgoingWeight();
            if (outgoingWeight == null) {
                outgoingWeight = 0.0;
            }
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(outgoingWeight));
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));

            BigDecimal add = bigDecimal.add(bigDecimal1);
            pickingSale.setOutgoingWeight(add.doubleValue());
            Integer outgoingNumber = pickingSale.getOutgoingNumber();
            if (outgoingNumber == null) {
                outgoingNumber = 0;
            }
            pickingSale.setOutgoingNumber(outgoingNumber + 1);

            //判断单位是否是kg
            if ("2".equals(publicGoods.getMaterialUnit())) {
                //实际量
                pickingSale.setActualNumber(pickingSale.getOutgoingWeight());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                //实际量
                BigDecimal dun = new BigDecimal("1000");
                BigDecimal outNum = new BigDecimal(String.valueOf(pickingSale.getOutgoingWeight()));
                BigDecimal divide = outNum.divide(dun);
                pickingSale.setActualNumber(divide.doubleValue());
            } else {
                //实际量
                pickingSale.setActualNumber(Double.parseDouble(pickingSale.getOutgoingNumber() + ""));
            }

            updateById(pickingSale);

            //修改仓库物料的状态为备料
            wmsStockInfo.setWsiMaterialStatus(5);
            int i = wmsStockInfoMapper.updateById(wmsStockInfo);


            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(pickingSale.getPlannedWeight() + "/" + pickingSale.getActualNumber() + unitMap.get(publicGoods.getMaterialUnit()));
            //出库数量
            pickingRestDbDto.setAllotNumOut(pickingSale.getOutgoingNumber() + "");

            pickingRestDbDto.setMessage("物料号码:" + inputValue + ",净重:" + wmsStockInfo.getWsiNetWeight() + ",数量:1" + "出库成功");


            OutboundLog outboundLog = new OutboundLog();
            BeanUtils.copyProperties(wmsStockInfo, outboundLog, new String[]{"id"});
            boolean save = outboundLogService.save(outboundLog);

            if (save) {
                BackDataVo backDataVo = new BackDataVo();
                backDataVo.setMaterialCode(pickingSale.getMaterialCode());
                backDataVo.setNetWeight(wmsStockInfo.getWsiNetWeight());
                backDataVo.setSaleNumber(pickingSale.getConnectionId());
                boolean b = orderFeignService.updateShippingWeight(backDataVo);
                if (!b) {
                    throw new GlobalException("服务调用失败");
                }
            } else {
                throw new GlobalException("出库异常");
            }

            //查询当前生产领料单
            PickingSale pickingSale1 = pickingSaleMapper.selectById(pickingRestDbVo.getId());
            //判断是否有超收
            int docHairMark = sysDocument.getDocHairMark();
            //没有超收
            if (docHairMark != 1 && publicGoods.getMaterialHair() != 1) {

                //如果是kg
                if ("2".equals(publicGoods.getMaterialUnit()) || "3".equals(publicGoods.getMaterialUnit())) {
                    //计划出库重量
                    Double allotAmount = pickingSale1.getPlannedWeight();
                    //实际出库重量
                    Double allotWeightOut = pickingSale1.getActualNumber();
                    if (allotWeightOut >= allotAmount) {
                        //判断是否有检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingSale.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingSale.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(3);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingSaleDetail> stockOutInfoDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getPdoductNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingSale1.setWodStatus(9);
                            pickingSaleMapper.updateById(pickingSale1);
                            pickingRestDbDto.setCode("200");
                            SchemeDto point = point(pickingRestDbVo.getId());
                            pickingRestDbDto.setPickingPrompt(point.getCombinationName());
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据为待交接
                            pickingSale1.setWodStatus(10);
                            pickingSaleMapper.updateById(pickingSale1);

                        } else {
                            //修改单据为已完成
                            pickingSale1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
                            pickingSaleMapper.updateById(pickingSale1);
                        }
                    }
                } else {
                    //计划出库重量
                    Double allotAmount = pickingSale1.getPlannedWeight();
                    //实际出库数量
                    Integer allotNumOut = pickingSale1.getOutgoingNumber();
                    if (allotNumOut >= allotAmount) {
                        //判断是否检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingSale.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingSale.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(3);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingSaleDetail> stockOutInfoDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getPdoductNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingSale1.setWodStatus(9);
                            pickingSaleMapper.updateById(pickingSale1);
                            pickingRestDbDto.setCode("200");
                            SchemeDto point = point(pickingRestDbVo.getId());
                            pickingRestDbDto.setPickingPrompt(point.getCombinationName());
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据明细为待交接
                            pickingSale1.setWodStatus(10);
                            pickingSaleMapper.updateById(pickingSale1);

                        } else {
                            //修改单据状态为已完成
                            pickingSale1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
                            pickingSaleMapper.updateById(pickingSale1);
                        }
                    }
                }
            }
            //拣货方案
            SchemeDto point = point(pickingRestDbVo.getId());


            if (point.getCombinationName() != null) {
                pickingRestDbDto.setPickingPrompt(point.getCombinationName());
            }

            pickingRestDbDto.setCode("200");


        } else if ("2".equals(type)) {
            //批次出库
            //查询当前批次对应单条码信息
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 2).notIn(WmsStockInfo::getWsiFreezeInfo, 1));

            if (wmsStockInfoList.size() == 0) {
                pickingRestDbDto.setMessage("500");
                pickingRestDbDto.setMessage("扫描失败,此批次在库存中数量为0");
                return pickingRestDbDto;
            }

            //查询当前批次(在库的重量之和)
            Double netWeight = wmsStockInfoMapper.getNetWeight(inputValue);

            //查询委外出库单中的物料编码
            PickingSale pickingSale = pickingSaleMapper.selectById(pickingRestDbVo.getId());

            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));

            List<PickingSaleDetail> list = new ArrayList<PickingSaleDetail>();

            List<OutboundLog> outboundLogList = new ArrayList<>();

            for (WmsStockInfo wmsStockInfo : wmsStockInfoList) {


                //扫描的物料编码
                String wsiMaterialCode = wmsStockInfo.getWsiMaterialCode();

                if (!pickingSale.getMaterialCode().equals(wsiMaterialCode)) {
                    pickingRestDbDto.setCode("500");
                    pickingRestDbDto.setMessage("扫描失败，请核实后扫描");
                    return pickingRestDbDto;
                }


                //新增生产领料明细
                PickingSaleDetail pickingSaleDetail = new PickingSaleDetail();

                //物料号码
                pickingSaleDetail.setPdoductNumber(wmsStockInfo.getWsiMaterialNumber());

                //物料状态
                pickingSaleDetail.setWodStatus(3);

                //关联单号
                pickingSaleDetail.setWodDocNum(pickingSale.getWodDocNum());

                //毛重
                pickingSaleDetail.setGrossWeight(wmsStockInfo.getWsiGorssWeight());

                //净重
                pickingSaleDetail.setNetWeight(wmsStockInfo.getWsiNetWeight());

                //出库数量
                pickingSaleDetail.setOutgoingNumber(1L);

                //批次号
                pickingSaleDetail.setBatchNumber(wmsStockInfo.getWsiMaterialBatch());

                //克重
                pickingSaleDetail.setGramWeight(wmsStockInfo.getWsiGrawWeight());

                //厚度
                pickingSaleDetail.setThick(wmsStockInfo.getWsiThick());

                //幅宽
                pickingSaleDetail.setBreadth(wmsStockInfo.getWsiWidth());
                //卷长
                pickingSaleDetail.setRollLength(wmsStockInfo.getWsiLength());


                //仓储信息
                pickingSaleDetail.setWarehouseInfo(wmsStockInfo.getWsiWarehourseInfo());

                //出库人
                pickingSaleDetail.setDepositor(SecurityUtils.getUsername());

                //出库时间
                pickingSaleDetail.setDeliveryTime(new Date());

                //判断是否有检验
                int docInspectionMark = sysDocument.getDocInspectionMark();
                //如果有检验
                if (docInspectionMark == 1) {
                    //修改单据明细为待检验
                    pickingSaleDetail.setWodStatus(1);
                } else {
                    //判断是否有交接
                    int docHandoverMark = sysDocument.getDocHandoverMark();
                    //有交接
                    if (docHandoverMark == 1) {
                        //修改单据明细为待交接
                        pickingSaleDetail.setWodStatus(2);
                    }
                }
                list.add(pickingSaleDetail);


                //修改出库重量和出库数量
                Double outgoingWeight = pickingSale.getOutgoingWeight();
                if (outgoingWeight == null) {
                    outgoingWeight = 0.0;
                }
                BigDecimal bigDecimal = new BigDecimal(String.valueOf(outgoingWeight));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wmsStockInfo.getWsiNetWeight()));

                BigDecimal add = bigDecimal.add(bigDecimal1);
                pickingSale.setOutgoingWeight(add.doubleValue());
                Integer outgoingNumber = pickingSale.getOutgoingNumber();
                if (outgoingNumber == null) {
                    outgoingNumber = 0;
                }

                pickingSale.setOutgoingNumber(outgoingNumber + 1);


                //修改仓库物料的状态为备料
                wmsStockInfo.setWsiMaterialStatus(5);

                OutboundLog outboundLog = new OutboundLog();
                BeanUtils.copyProperties(wmsStockInfo, outboundLog, new String[]{"id"});
                outboundLogList.add(outboundLog);

            }

            //添加明细
            pickingSaleDetailService.saveBatch(list);
            wmsStockInfoService.updateBatchById(wmsStockInfoList);

            //修改生产领料单的单据状态为出库中
            pickingSale.setWodStatus(6);
            //判断单位是否是kg
            if ("2".equals(publicGoods.getMaterialUnit())) {
                //实际量
                pickingSale.setActualNumber(pickingSale.getOutgoingWeight());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                //实际量
                BigDecimal dun = new BigDecimal("1000");
                BigDecimal outNum = new BigDecimal(String.valueOf(pickingSale.getOutgoingWeight()));
                BigDecimal divide = outNum.divide(dun);
                pickingSale.setActualNumber(divide.doubleValue());
            } else {
                //实际量
                pickingSale.setActualNumber(Double.parseDouble(pickingSale.getOutgoingNumber() + ""));
            }
            updateById(pickingSale);


            PickingSale pickingSale1 = pickingSaleMapper.selectById(pickingRestDbVo.getId());
            //返回前端参数
            //计划/实际
            pickingRestDbDto.setQuantityIdentification(pickingSale1.getPlannedWeight() + "/" + pickingSale1.getActualNumber() + unitMap.get(publicGoods.getMaterialUnit()));
            //出库数量
            pickingRestDbDto.setAllotNumOut(pickingSale1.getOutgoingNumber() + "");


            pickingRestDbDto.setMessage("批次号:" + inputValue + ",总净重:" + netWeight + ",数量:" + wmsStockInfoList.size() + "出库成功");


            boolean save = outboundLogService.saveBatch(outboundLogList);
            if (save) {
                BackDataVo backDataVo = new BackDataVo();
                backDataVo.setMaterialCode(pickingSale.getMaterialCode());
                backDataVo.setNetWeight(netWeight);
                backDataVo.setSaleNumber(pickingSale.getConnectionId());
                orderFeignService.updateShippingWeight(backDataVo);
            } else {
                throw new GlobalException("出库异常");
            }


            //判断是否有超发
            int docHairMark = sysDocument.getDocHairMark();
            //没有超收
            if (docHairMark != 1 && publicGoods.getMaterialHair() != 1) {

                //如果是kg
                if ("2".equals(publicGoods.getMaterialUnit()) || "3".equals(publicGoods.getMaterialUnit())) {
                    //计划出库重量
                    Double allotAmount = pickingSale1.getPlannedWeight();
                    //实际出库重量
                    Double allotWeightOut = pickingSale1.getActualNumber();
                    if (allotWeightOut >= allotAmount) {
                        //判断是否有检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingSale.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingSale.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(3);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingSaleDetail> stockOutInfoDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getPdoductNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingSale1.setWodStatus(9);
                            pickingSaleMapper.updateById(pickingSale1);
                            pickingRestDbDto.setCode("200");
                            SchemeDto point = point(pickingRestDbVo.getId());
                            pickingRestDbDto.setPickingPrompt(point.getCombinationName());
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据为待交接
                            pickingSale1.setWodStatus(10);
                            pickingSaleMapper.updateById(pickingSale1);

                        } else {
                            //修改单据为已完成
                            pickingSale1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 5));
                            pickingSaleMapper.updateById(pickingSale1);
                        }
                    }
                } else {
                    //计划出库重量
                    Double allotAmount = pickingSale1.getPlannedWeight();
                    //实际出库数量
                    Integer allotNumOut = pickingSale1.getOutgoingNumber();
                    if (allotNumOut >= allotAmount) {
                        //判断是否检验或者交接
                        //判断是否有检验
                        int isDocInspectionMark = sysDocument.getDocInspectionMark();
                        //如果有检验
                        if (isDocInspectionMark == 1) {
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            //添加类别，编码，物料类别
                            qualityInspectionDocumentVo.setMaterialCode(pickingSale.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setAssociatedNo(pickingSale.getWodDocNum());
                            qualityInspectionDocumentVo.setModeType(3);
                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
                            //查询当前明细表中的所有物料号码
                            List<PickingSaleDetail> stockOutInfoDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                            String batchNum = "";

                            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                                if (j == 0) {
                                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                                } else {
                                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                                    }
                                }

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getPdoductNumber());
                                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setBatchNo(batchNum);

                            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
                            //修改单据为待检验
                            pickingSale1.setWodStatus(9);
                            pickingSaleMapper.updateById(pickingSale1);
                            pickingRestDbDto.setCode("200");
                            SchemeDto point = point(pickingRestDbVo.getId());
                            pickingRestDbDto.setPickingPrompt(point.getCombinationName());
                            return pickingRestDbDto;
                        }
                        //判断是否有交接
                        int docHandoverMark = sysDocument.getDocHandoverMark();
                        //有交接
                        if (docHandoverMark == 1) {
                            //修改单据明细为待交接
                            pickingSale1.setWodStatus(10);
                            pickingSaleMapper.updateById(pickingSale1);

                        } else {
                            //修改单据状态为已完成
                            pickingSale1.setWodStatus(7);
                            //删除库存
                            wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 5));
                            pickingSaleMapper.updateById(pickingSale1);
                        }
                    }
                }
            }
            pickingRestDbDto.setCode("200");

        } else if ("3".equals(type)) {
            //条码撤销
            PickingSale pickingSale = pickingSaleMapper.selectById(pickingRestDbVo.getId());

            if (pickingSale.getWodStatus() != 5 && pickingSale.getWodStatus() != 6) {
                throw new GlobalException("只能对待出库和出库中的单据进行条码撤销");
            }

            //在明细表中查询是否有此条码
            PickingSaleDetail pickingSaleDetail = pickingSaleDetailMapper.selectOne(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getPdoductNumber, inputValue).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));
            if (pickingSaleDetail == null) {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("撤销失败");
                return pickingRestDbDto;
            }

            //修改库存状态为在库
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
            wmsStockInfo.setWsiMaterialStatus(2);
            wmsStockInfoMapper.updateById(wmsStockInfo);


            OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, inputValue));

            //删除日志
            outboundLogService.removeById(outboundLog);

            //删除出库明细
            int delete = pickingSaleDetailMapper.delete(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getPdoductNumber, inputValue).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));


            BigDecimal out = new BigDecimal(String.valueOf(pickingSale.getOutgoingWeight()));
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(pickingSaleDetail.getNetWeight()));
            BigDecimal outWeight = out.subtract(bigDecimal);
            //修改出库重量
            pickingSale.setOutgoingWeight(outWeight.doubleValue());

            //扣除数量
            Integer outgoingNumber = pickingSale.getOutgoingNumber();
            pickingSale.setOutgoingNumber(outgoingNumber - 1);

            //查询单位
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));

            //实际出库重量
            if ("2".equals(publicGoods.getMaterialUnit())) {

                BigDecimal sj = new BigDecimal(String.valueOf(pickingSale.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(pickingSaleDetail.getNetWeight()));
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                pickingSale.setActualNumber(sjWeight.doubleValue());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                BigDecimal sj = new BigDecimal(String.valueOf(pickingSale.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(pickingSaleDetail.getNetWeight())).divide(new BigDecimal("1000"));
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                pickingSale.setActualNumber(sjWeight.doubleValue());
            } else {
                BigDecimal sj = new BigDecimal(String.valueOf(pickingSale.getActualNumber()));
                BigDecimal bigDecimal1 = new BigDecimal("1");
                BigDecimal sjWeight = sj.subtract(bigDecimal1);
                pickingSale.setActualNumber(sjWeight.doubleValue());

            }

            int i = pickingSaleMapper.updateById(pickingSale);
            if (i <= 0) {
                pickingRestDbDto.setMessage("撤销失败");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            } else {
                BackDataVo backDataVo = new BackDataVo();
                backDataVo.setMaterialCode(pickingSale.getMaterialCode());
                backDataVo.setNetWeight(pickingSaleDetail.getNetWeight());
                backDataVo.setSaleNumber(pickingSale.getConnectionId());
                orderFeignService.updateShippingWeightSub(backDataVo);
            }
            //删除品质检验单
            pickingRestDbDto.setMessage("撤销成功");
        }

        pickingRestDbDto.setCode("200");
        SchemeDto point = point(pickingRestDbVo.getId());
        pickingRestDbDto.setPickingPrompt(point.getCombinationName());
        return pickingRestDbDto;
    }

    /**
     * 拣货完成
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean finishProduction(Long id) throws Exception {
        //判断当前页面是否有配置送检和交接，如果有则生成品检单

        //获取菜单id
        Long menuId = feignService.getIdByMenuName("销售发货");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = com.alibaba.fastjson2.JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

        //查出销售发货信息单
        PickingSale pickingSale = pickingSaleMapper.selectById(id);

        //判断是否有检验
        int docInspectionMark = sysDocument.getDocInspectionMark();
        //如果有检验
        if (docInspectionMark == 1) {
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));
            //生成品质检验单
            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
            //添加类别，编码，物料类别
            qualityInspectionDocumentVo.setMaterialCode(pickingSale.getMaterialCode());
            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
            qualityInspectionDocumentVo.setAssociatedNo(pickingSale.getWodDocNum());
            qualityInspectionDocumentVo.setModeType(3);
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoVos = new ArrayList<>();
            //查询当前明细表中的所有物料号码
            List<PickingSaleDetail> stockOutInfoDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

            String batchNum = "";

            for (int j = 0; j < stockOutInfoDetailList.size(); j++) {
                if (j == 0) {
                    batchNum = stockOutInfoDetailList.get(j).getBatchNumber();
                } else {
                    if (!batchNum.equals(stockOutInfoDetailList.get(j).getBatchNumber())) {
                        batchNum = batchNum + "," + stockOutInfoDetailList.get(j).getBatchNumber();
                    }
                }

                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                materialNumberAndBatchNoVo.setMaterialNumber(stockOutInfoDetailList.get(j).getPdoductNumber());
                materialNumberAndBatchNoVo.setBatchNo(stockOutInfoDetailList.get(j).getBatchNumber());
                materialNumberAndBatchNoVo.setMaterialCategory(publicGoods.getMaterialCategory());
                materialNumberAndBatchNoVos.add(materialNumberAndBatchNoVo);
            }
            qualityInspectionDocumentVo.setBatchNo(batchNum);

            productionPickingService.insertQuality(sysDocument, qualityInspectionDocumentVo, materialNumberAndBatchNoVos);
            //修改单据状态为待检验
            pickingSale.setWodStatus(9);
            return pickingSaleMapper.updateById(pickingSale) > 0;
        }

        //判断是否有交接
        int docHandoverMark = sysDocument.getDocHandoverMark();
        //有交接
        if (docHandoverMark == 1) {
            //修改单据状态为待交接
            pickingSale.setWodStatus(10);
            return pickingSaleMapper.updateById(pickingSale) > 0;
        }

        //判断是否有超收
        int docHairMark = sysDocument.getDocHairMark();

        //修改单据状态为已完成
        pickingSale.setWodStatus(7);

        //删除库存
        List list = new ArrayList<WmsStockInfo>();

        List<PickingSaleDetail> pickingSaleDetailList3 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

        for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList3) {
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingSaleDetail.getPdoductNumber()));
            list.add(wmsStockInfo);
        }
        wmsStockInfoMapper.deleteBatchIds(list);

        return pickingSaleMapper.updateById(pickingSale) > 0;
    }

    /**
     * 拣货撤销
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean repealProduction(Long id) {
        //修改单据状态为待出库
        PickingSale pickingSale = pickingSaleMapper.selectById(id);
        pickingSale.setWodStatus(5);
        //实际重量，出库重量，出库数量清空
        pickingSale.setActualNumber(0.0);
        pickingSale.setOutgoingNumber(0);
        pickingSale.setOutgoingWeight(0.0);
        //交接数量，交接重量清空
        pickingSale.setOverWeight(0.0);
        pickingSale.setOverNum(0);
        pickingSaleMapper.updateById(pickingSale);

        //查询明细
        List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

        //日志表集合
        List<OutboundLog> outboundLogList = new ArrayList<>();

        //遍历
        for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList) {
            //将仓库中的物料全修改为在库
            //修改仓库状态为在库
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingSaleDetail.getPdoductNumber()));
            wmsStockInfo.setWsiMaterialStatus(2);
            wmsStockInfoMapper.updateById(wmsStockInfo);

            OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, wmsStockInfo.getWsiMaterialNumber()));
            outboundLogList.add(outboundLog);
        }
        //删除日志表中的数据
        outboundLogService.removeBatchByIds(outboundLogList);

        //删除品质检验单
        qualityFeginService.removeDoc(pickingSale.getWodDocNum());
        //删除所有明细
        int i = pickingSaleDetailMapper.delete(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

        return i > 0;
    }

    /**
     * 交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestHandoverDto overProduction(PickingRestDbVo pickingRestDbVo) {
        //获取步骤
        int step = pickingRestDbVo.getExecutionOrder();
        //获取输入值
        String inputValue = pickingRestDbVo.getInputValue();
        //返回值
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();
        //获取菜单id
        Long menuId = feignService.getIdByMenuName("销售发货");
        //交接方式
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //拿到交接方式
        int jjType = sysDocument.getDocHandoverMethod();

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        if (step == 1) {


            //校验员工编号
            AjaxResult byUserName = remoteUserService.getByUserName(pickingRestDbVo.getInputValue());
            SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

            if (userInfo.getUserName() == null) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                return pickingRestHandoverDto;
            }

            //返回交接人
            pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
            pickingRestHandoverDto.setDocHandoverMethod(jjType);


            if (jjType == 1) {
                pickingRestHandoverDto.setMessage("请输入物料条码");
            } else if (jjType == 2) {
                pickingRestHandoverDto.setMessage("请输入批次号");
            } else if (jjType == 3) {
                PickingSale pickingSale = pickingSaleMapper.selectById(pickingRestDbVo.getId());

                pickingRestDbVo.setInputValue(pickingSale.getWodDocNum());

                //查询物料单位
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));

                //判断是否存在明细表中
                List<PickingSaleDetail> pickingSaleDetailList1 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingRestDbVo.getInputValue()));
                if (pickingSaleDetailList1 == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //查询当前单据号在明细中是否存在，且状态为待交接
                List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingRestDbVo.getInputValue()).eq(PickingSaleDetail::getWodStatus, 2));
                if (pickingSaleDetailList.size() == 0) {
                    pickingRestHandoverDto.setMessage("交接失败,请核实后再录入");
                    pickingRestHandoverDto.setResultCode("500");
                    return pickingRestHandoverDto;
                } else {
                    //查出当前为待交接状态的单据明细,算出总净重和总数量
                    Double sumPiHao = pickingSaleDetailMapper.getDoc(pickingRestDbVo.getInputValue());
                    //总数量
                    long sumNum = pickingSaleDetailList.size();

                    //出库重量
                    Double allotAmount = pickingSale.getOutgoingWeight();

                    //返回计划/实际

                    //(实际交接)
                    Double overWeight = pickingSale.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(sumPiHao));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    pickingSale.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitMap.get(publicGoods.getMaterialUnit()));


                    //保存交接数量，交接重量
                    Integer overNum = pickingSale.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    int jjSum = (int) sumNum;
                    pickingSale.setOverNum(overNum + jjSum);

                    //取出关节人
                    String closeUser = pickingSale.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = SecurityUtils.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        pickingSale.setCloseMan(name);
                    }


                    if (jj == 1) {
                        pickingSale.setCloseMan("," + name);
                    }
                    pickingSale.setCloseTime(new Date());

                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(pickingSale.getOutgoingNumber() + "/" + pickingSale.getOverNum());

                    for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList) {
                        //修改物料状态明细为已出库
                        pickingSaleDetail.setWodStatus(3);
                        pickingSaleDetailMapper.updateById(pickingSaleDetail);
                    }


                    //判断是否所有物料没有待交接的状态
                    List<PickingSaleDetail> pickingSaleDetailList2 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodStatus, 2).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                    if (pickingSaleDetailList2.size() == 0) {
                        //修改单据状态为已完成
                        pickingSale.setWodStatus(7);
                        //删除库存
                        List list = new ArrayList<WmsStockInfo>();

                        List<PickingSaleDetail> pickingSaleDetailList3 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                        for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList3) {
                            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingSaleDetail.getPdoductNumber()));
                            list.add(wmsStockInfo);
                        }
                        wmsStockInfoMapper.deleteBatchIds(list);

                    }
                    boolean b = updateById(pickingSale);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("单据号:" + pickingRestDbVo.getInputValue() + ",总净重" + sumPiHao + "数量:" + sumNum + ",交接成功");
                }
            }
            pickingRestHandoverDto.setResultCode("200");
            return pickingRestHandoverDto;

        } else if (step == 2) {
            //如果是单个物料交接
            if (jjType == 1) {
                //查询当前的出库单信息
                PickingSale pickingSale = pickingSaleMapper.selectById(pickingRestDbVo.getId());

                //查询物料单位
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));


                //查询出库明细
                PickingSaleDetail pickingSaleDetail = pickingSaleDetailMapper.selectOne(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getPdoductNumber, inputValue).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));
                if (pickingSaleDetail == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接失败");
                    return pickingRestHandoverDto;
                }

                //判断当前物料是否属于待交接
                if (pickingSaleDetail.getWodStatus() != 2) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("不可重复交接");
                    return pickingRestHandoverDto;
                } else {
                    //出库重量
                    Double allotAmount = pickingSale.getOutgoingWeight();

                    Double overWeight = pickingSale.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    //(实际交接)
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(pickingSaleDetail.getNetWeight()));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    pickingSale.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitMap.get(publicGoods.getMaterialUnit()));


                    //保存交接数量，交接重量
                    Integer overNum = pickingSale.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    pickingSale.setOverNum(overNum + 1);

                    //取出关节人
                    String closeUser = pickingSale.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = SecurityUtils.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        pickingSale.setCloseMan(name);
                    }


                    if (jj == 1) {
                        pickingSale.setCloseMan("," + name);
                    }
                    pickingSale.setCloseTime(new Date());
                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(pickingSale.getOutgoingNumber() + "/" + pickingSale.getOverNum());

                    //修改物料状态明细为已出库
                    pickingSaleDetail.setWodStatus(3);
                    pickingSaleDetailMapper.updateById(pickingSaleDetail);


                    //判断是否所有物料没有待交接的状态
                    List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodStatus, 2).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));
                    if (pickingSaleDetailList.size() == 0) {
                        //修改单据状态为已完成
                        pickingSale.setWodStatus(7);
                        //删除库存
                        List list = new ArrayList<WmsStockInfo>();

                        List<PickingSaleDetail> pickingSaleDetailList3 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                        for (PickingSaleDetail pickingSaleDetail11 : pickingSaleDetailList3) {
                            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingSaleDetail11.getPdoductNumber()));
                            list.add(wmsStockInfo);
                        }
                        wmsStockInfoMapper.deleteBatchIds(list);
                    }

                    boolean b = updateById(pickingSale);
                    if (!b) {
                        pickingRestHandoverDto.setResultCode("500");
                        pickingRestHandoverDto.setMessage("交接失败");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("物料号码:" + pickingRestDbVo.getInputValue() + ",净重" + pickingSaleDetail.getNetWeight() + "数量:1,交接成功");

                }
            } else if (jjType == 2) {
                PickingSale pickingSale = pickingSaleMapper.selectById(pickingRestDbVo.getId());

                //查询物料单位
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSale.getMaterialCode()));

                //判断是否存在明细表中
                List<PickingSaleDetail> pickingSaleDetailList1 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getBatchNumber, pickingRestDbVo.getInputValue()).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));
                if (pickingSaleDetailList1 == null) {
                    pickingRestHandoverDto.setMessage("交接失败,请核实后再录入");
                    pickingRestHandoverDto.setResultCode("500");
                    return pickingRestHandoverDto;
                }

                //查询当前批号在明细中是否存在，且状态为待交接
                List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getBatchNumber, pickingRestDbVo.getInputValue()).eq(PickingSaleDetail::getWodStatus, 2).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));
                if (pickingSaleDetailList.size() == 0) {
                    pickingRestHandoverDto.setMessage("不可重复交接");
                    pickingRestHandoverDto.setResultCode("500");
                    return pickingRestHandoverDto;
                } else {
                    //查出当前为待交接状态的批次，算出总净重和总数量
                    Double sumPiHao = pickingSaleDetailMapper.getPiHao(pickingRestDbVo.getInputValue());
                    //总数量
                    long sumNum = pickingSaleDetailList.size();

                    //出库重量
                    Double allotAmount = pickingSale.getOutgoingWeight();

                    //返回计划/实际

                    //(实际交接)
                    Double overWeight = pickingSale.getOverWeight();
                    if (overWeight == null) {
                        overWeight = 0.0;
                    }
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(overWeight));
                    //查询号码在明细中的重量
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(sumPiHao));
                    BigDecimal add = bigDecimal.add(bigDecimal1);

                    pickingSale.setOverWeight(add.doubleValue());

                    pickingRestHandoverDto.setQuantityIdentification(allotAmount + "/" + add.toString() + unitMap.get(publicGoods.getMaterialUnit()));


                    //保存交接数量，交接重量
                    Integer overNum = pickingSale.getOverNum();
                    if (overNum == null) {
                        overNum = 0;
                    }
                    int jjSum = (int) sumNum;
                    pickingSale.setOverNum(overNum + jjSum);

                    //取出关节人
                    String closeUser = pickingSale.getCloseMan();
                    if (closeUser == null) {
                        closeUser = "";
                    }
                    String[] split = closeUser.split(",");

                    //获取交接人名称
                    String name = SecurityUtils.getUsername();

                    //定义变量记录交接人是否相等
                    int jj = 0;

                    if (closeUser != null && !"".equals(closeUser)) {
                        for (String s : split) {
                            if (!name.equals(s)) {
                                jj = 1;
                            }
                        }
                    } else {
                        pickingSale.setCloseMan(name);
                    }


                    if (jj == 1) {
                        pickingSale.setCloseMan("," + name);
                    }
                    pickingSale.setCloseTime(new Date());


                    //出库/交接
                    pickingRestHandoverDto.setOutHandoverActual(pickingSale.getOutgoingNumber() + "/" + pickingSale.getOverNum());

                    for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList) {
                        //修改物料状态明细为已出库
                        pickingSaleDetail.setWodStatus(3);
                        pickingSaleDetailMapper.updateById(pickingSaleDetail);
                    }


                    //判断是否所有物料没有待交接的状态
                    List<PickingSaleDetail> pickingSaleDetailList2 = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodStatus, 2).eq(PickingSaleDetail::getWodDocNum, pickingSale.getWodDocNum()));

                    if (pickingSaleDetailList2.size() == 0) {
                        //修改单据状态为已完成
                        pickingSale.setWodStatus(7);

                        //删除库存
                        wmsStockInfoMapper.delete(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 5));

                    }
                    boolean b = updateById(pickingSale);
                    if (!b) {
                        pickingRestHandoverDto.setMessage("交接失败");
                        pickingRestHandoverDto.setResultCode("500");
                        return pickingRestHandoverDto;
                    }

                    //消息提示
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + ",总净重" + sumPiHao + "数量:" + sumNum + ",交接成功");
                }
            } else if (jjType == 3) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("请勿重复交接");

            }
        }
        pickingRestHandoverDto.setResultCode("200");
        return pickingRestHandoverDto;
    }

    /**
     * 销售发货审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saleReview(OrderReviewVo orderReviewVo) {

        PickingSale pickingSale = getById(orderReviewVo.getId());
        if (pickingSale.getWodStatus() == 2 || pickingSale.getWodStatus() == 3) {
            String perms = "warehouse:outbound:shipsale:examine";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = pickingSale.getWodDocNum();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 9, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    pickingSale.setWodStatus(5);
                    if (pickingSale.getReviewBy() == null) {
                        pickingSale.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingSale.setReviewBy(pickingSale.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingSale.setReviewTime(new Date());

                    feignService.updateStatus(3, pickingSale.getWodDocNum(), "销售发货");

                    return updateById(pickingSale);
                } else if (data == 2) {
                    pickingSale.setWodStatus(3);
                    if (pickingSale.getReviewBy() == null) {
                        pickingSale.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingSale.setReviewBy(pickingSale.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingSale.setReviewTime(new Date());
                    return updateById(pickingSale);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    pickingSale.setWodStatus(4);
                    if (pickingSale.getReviewBy() == null) {
                        pickingSale.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingSale.setReviewBy(pickingSale.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingSale.setReviewTime(new Date());

                    SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
                    sysWorkbenchAuditAgentVo.setDocConfig("warehouse:outbound:shipsale:examine");
                    sysWorkbenchAuditAgentVo.setReceiptName("销售发货");
                    sysWorkbenchAuditAgentVo.setReceiptNumber(pickingSale.getWodDocNum());//
                    sysWorkbenchAuditAgentVo.setStatus(2);//待处理
                    sysWorkbenchAuditAgentVo.setReceiptContent("有单据未通过,请及时查看");

                    sysWorkbenchAuditAgentVo.setPassFlag("1");
                    sysWorkbenchAuditAgentVo.setCreateName(pickingSale.getCreateUser());

                    feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                    return updateById(pickingSale);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }

    }

    /**
     * 销售发货修改品质
     *
     * @param updateDocVo
     * @return
     */
    @Override
    public boolean saleUpdateStatus(UpdateDocVo updateDocVo) {
        //获取菜单id
        Long menuId = feignService.getIdByMenuName("销售发货");
        //交接方式
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //交接方式
        int docHandoverMethod = sysDocument.getDocHandoverMark();

        //判断是否有交接

        //如果有交接，修改单据状态和物料明细状态为代交接
        if (docHandoverMethod == 1) {
            PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda().eq(PickingSale::getWodDocNum, updateDocVo.getDocNum()));
            pickingSale.setWodStatus(10);//待交接
            updateById(pickingSale);
            List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, updateDocVo.getDocNum()));
            for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList) {
                pickingSaleDetail.setWodStatus(2);
            }
            return pickingSaleDetailService.updateBatchById(pickingSaleDetailList);

        } else {
            PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda().eq(PickingSale::getWodDocNum, updateDocVo.getDocNum()));
            pickingSale.setWodStatus(7);//已完成
            updateById(pickingSale);
            List<PickingSaleDetail> pickingSaleDetailList = pickingSaleDetailMapper.selectList(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getWodDocNum, updateDocVo.getDocNum()));

            List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();
            for (PickingSaleDetail pickingSaleDetail : pickingSaleDetailList) {
                pickingSaleDetail.setWodStatus(3);
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingSaleDetail.getPdoductNumber()));
                wmsStockInfoList.add(wmsStockInfo);
            }
            wmsStockInfoService.removeBatchByIds(wmsStockInfoList);
            return pickingSaleDetailService.updateBatchById(pickingSaleDetailList);
        }

    }

    @Override
    public SchemeDto point(Long id) {
        PickingSale byId = getById(id);
        SchemeVo schemeVo = new SchemeVo();
        schemeVo.setMaterialCode(byId.getMaterialCode());
        schemeVo.setAssociatedDetails("3");
        return pickingSchemeService.getSchemeData(schemeVo);
    }

    /**
     * 查询销售发货列表(feign调用) 客诉管理查询使用
     *
     * @param pickingSaleVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<PickingSaleDto> getByCustomerComplaintsList(PickingSaleVo pickingSaleVo) {
        //查询销售发货列表
        List<PickingSaleDto> pickingSaleList = pickingSaleMapper.getPickingSaleList(pickingSaleVo);

        //获取单据状态字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("picking_sale_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出收发类型
        List<SysDictData> receivType = DictUtils.getDictCache("picking_sale_type");
        Map<String, String> typeMap = receivType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据字典查出单位
        List<SysDictData> unitList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //新建一个dto集合
        List dtoList = new ArrayList();
        for (PickingSaleDto pickingSaleDto : pickingSaleList) {

            //查看仓库名称
            Warehouse warehouse = warehouseMapper.selectById(pickingSaleDto.getOutOfStock());
            if (warehouse != null) {
                //添加仓库名称
                pickingSaleDto.setOutOfStockDict(warehouse.getWarehouseName());
                pickingSaleDto.setOutOfStock(pickingSaleDto.getOutOfStock());
            }


            //添加单据类型
            pickingSaleDto.setDocumentType(DocumentTypeEnum.getValue(Integer.parseInt(pickingSaleDto.getDocumentType())));

            //添加收发类型
            pickingSaleDto.setTransceiverTypeDict(pickingSaleDto.getTransceiverType() + "");
            pickingSaleDto.setTransceiverType(typeMap.get(pickingSaleDto.getTransceiverType() + ""));


            //添加单据状态
            pickingSaleDto.setWodStatusDict(pickingSaleDto.getWodStatus() + "");
            pickingSaleDto.setWodStatus(statusMap.get(pickingSaleDto.getWodStatus() + ""));

            //添加生产方式
            pickingSaleDto.setGenerationMode(GenerationMethodEnum.getValue(Integer.parseInt(pickingSaleDto.getGenerationMode())));

            //添加单位key
            pickingSaleDto.setMaterialUnitDict(pickingSaleDto.getMaterialUnit() + "");

            //添加单位值
            pickingSaleDto.setMaterialUnit(unitMap.get(pickingSaleDto.getMaterialUnit() + ""));

            dtoList.add(pickingSaleDto);

        }
        return dtoList;
    }


}
